package com.bestom.waterquality.logic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import com.bestom.waterquality.R;

import java.io.File;

import static com.hikvision.open.hikvideoplayer.HikVideoPlayerFactory.finish;

/**
 * 恢复出厂设置
 */
public class FactoryReset {

    private Context mContext;
    private Activity mActivity;

    private FactoryReset() {
    }

    private static FactoryReset _instance = null;

    public static FactoryReset getInstance() {
        if (_instance == null)
            _instance = new FactoryReset();
        return _instance;
    }

    public void setDataAndListen(Activity activity, Context context, View view){

        if (mContext == null){
            mContext = context;
            mActivity = activity;
            view.findViewById(R.id.initialize).setOnClickListener(v -> new AlertDialog.Builder(mContext)
                    .setTitle("清除所有数据")
                    .setMessage("此操作会清除您内部存储设备中的所有数据，您确定要继续吗？")
                    .setPositiveButton("确定", (dialog, which) -> {

                        deleteFile(new File("data/data/"+ mContext.getPackageName()));
                        //重启应用
                        reStartActivity();
                        //   第一个参为包名，第二个各个设置的类名(可以参考下面，包名不用改变)
                    /*Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,"com.android.settings.MasterClear");//要启动的fragment
                    intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS,true);
                    intent.setClassName("com.android.settings","com.android.settings.SubSettings");//包名，要启动fragment所依赖的Activity
                    intent.putExtra(":settings:show_fragment_as_subsetting", true);
                    mContext.startActivity(intent);*/

                    })
                    .setNegativeButton("取消", null)
                    .show());
        }
    }

    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
                return;
            }
            if (file.isDirectory()) {
                File[] childFile = file.listFiles();
                if (childFile == null || childFile.length == 0) {
                    file.delete();
                    return;
                }
                for (File f : childFile) {
                    deleteFile(f);
                }
                file.delete();
            }
        }
    }

    private void reStartActivity() {
        Intent intent = mActivity.getIntent();
        mActivity.finish();
        mActivity.startActivity(intent);
    }
}
